package ios.di.logviewer.data;

import ios.di.logviewer.util.DateUtil;

import java.io.File;
import java.io.FileFilter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日志文件过滤器，根据日志文件名（包含一个日期）来过滤掉无关的日志文件
 * @author LuoHouQi
 *
 */
public class LogFileFilter implements FileFilter {
	private Date happenDayStart,happenDayEnd;
	
	
	
	public void setHappenDateStart(Date happenDateStart) {
		if(happenDateStart!=null)
		{
		this.happenDayStart = new Date(happenDateStart.getTime());
		
		//将happenDayStart设置成这一天的最开始（将其时、分、秒初始化为0）
		this.happenDayStart.setHours(0);
		this.happenDayStart.setMinutes(0);
		this.happenDayStart.setSeconds(0);
		}
		
	}

	public void setHappenDateEnd(Date happenDateEnd) {
		if (happenDateEnd != null) {
			this.happenDayEnd = new Date(happenDateEnd.getTime());
			
			// 将happenDayStart设置成这一天的最后一秒
			this.happenDayEnd.setHours(23);
			this.happenDayEnd.setMinutes(59);
			this.happenDayEnd.setSeconds(59);
		}
	}
	
	public boolean accept(File file)
	{
		
		int apenIdx = file.getName().indexOf('.');
		if(apenIdx==-1)
			return false;
		String fileNmae = file.getName().substring(0, apenIdx);
		try {
			Date fileDate = DateUtil.getDateUtil(DateUtil.PATTERN_2).parseDate(fileNmae);
			if(fileDate==null)
				return false;
			else if(this.happenDayStart!=null && this.happenDayStart.after(fileDate))
				return false;
			else if(this.happenDayEnd!=null && this.happenDayEnd.before(fileDate))
				return false;
			else
				return true;
			
		} catch (ParseException e) {
			e.printStackTrace();
			System.out.println(file.getName()+"的文件名不合法");
			return false;
		}
		
	}
	
}
